const https = require('https');
const fs = require('fs');
const path = require('path');

let heroList = null;
fs.readFile(path.join(__dirname, 'data/herolist.json'), (err, data) => {
  data = JSON.parse(data);
  heroList = data; // 获取英雄数据 
  // heroList = data.filter((v, i) => i < 5);
  // 创建目录 
  heroList.forEach((v, index) => {
    fs.mkdir(`./images/${v.cname}`, () => console.log(`${v.cname} 创建完成`));
    let length = v.skin_name.split('|').length;
    //定时器延迟 
    setTimeout(() => {
      for (let i = 1; i <= length; i++) {
        // 下载当前英雄的第i张图片
        getImage(v, i);
      }
    }, index * 1500);
  })
})


// 爬图片
function getImage (item, index) {

  let url = `https://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/${item.ename}/${item.ename}-bigskin-${index}.jpg`;
  console.log('url:', url);
  const options = new URL(url);
  const req = https.request(options, (res) => {
    console.log('请求已发送了');

    let imgData = "";
    res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开
    res.on("data", function (chunk) { //这步是我百度来的。。。。
      imgData += chunk;
    });

    res.on("end", function () {
      fs.writeFile(`./images/${item.cname}/${index}.jpg`, imgData, "binary", function (err) {
        if (err) {
          console.log(`图片${item.cname}-${index}.jpg保存失败`);
        }
        console.log(`图片${item.cname}-${index}.jpg保存成功`);
      });
    });
  });

  req.on('error', (e) => {
    console.error('请求出错');
  });

  req.end();
}
